package org.arcg_learn.spring_cloud.scn_homework.service_gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class OperationCountFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${rate-limiter.interval-in-minutes}")
    private Integer expireMinutes;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> strings = request.getHeaders().get("x-realIp");
        String realIp = strings.get(0);
        String key = "operation_count:" + realIp;
        stringRedisTemplate.opsForValue().increment(key);
        stringRedisTemplate.expire(key,expireMinutes, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
